package kr.co.exight.onApp;

import library.GCMHttpConnect;
import library.Variables;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {
	private static final String TAG = "GCM";
	private static final String SENDER_ID = "242049221661";
	
	public GCMIntentService() {
		super(SENDER_ID);
	}
	
	public GCMIntentService(String senderId) {
		super(senderId);
	}

	@Override
	public void onMessage(Context context, Intent intent) {
		if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
			showMessage(context, intent);
		}
	}

	@Override
	public void onError(Context context, String msg) {
		// TODO Auto-generated method stub
		Log.w(TAG, "onError!! " + msg);
	}

	

	@Override
	public void onRegistered(Context context, String regID) {
		// TODO Auto-generated method stub
		if(!regID.equals("") || regID != null){
			Log.w(TAG, "onRegistered!! " + regID);

			insertRegistrationID(context, regID);
		}
	}

	@Override
	public void onUnregistered(Context context, String regID) {
		// TODO Auto-generated method stub
		Log.w(TAG, "onUnregistered!! " + regID);
	}
	
	public void showToast(){
		Toast.makeText(this, "RegID 등록됨.", Toast.LENGTH_LONG).show();
	}
	
	private void showMessage(Context context, Intent intent){
		//String title = intent.getStringExtra("title");
		String msg = intent.getStringExtra("msg");
		//String ticker = intent.getStringExtra("ticker");
		
		NotificationManager notificationManager = (NotificationManager)context.getSystemService(Activity.NOTIFICATION_SERVICE);
		
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
				new Intent(context, ActivityTabOncard.class)
		.putExtra("MODE", 2)
		.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
		
		Notification notification = new Notification();
		notification.defaults = Notification.DEFAULT_SOUND;
		notification.icon = R.drawable.icon_push; // 변경할것.
		notification.tickerText = msg;
		notification.when = System.currentTimeMillis();
		notification.vibrate = new long[] { 500, 100, 300 };
		//notification.sound = Uri.parse("/system/media/audio/notifications/20_Cloud.ogg");
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notification.setLatestEventInfo(context, "ON APP 알림" , msg, pendingIntent);
		
		notificationManager.notify(0, notification);
	}
	
	
	
	
	
	public void insertRegistrationID(Context context, String id){
		GCMHttpConnect httpConnect = new GCMHttpConnect(context, Variables.NOTIFICATION_ADD_URL + id + "/add", 0);
		httpConnect.start();
	}
}
